<template>
  <main-card-admin title="学习案例" :loading="globalLoading" :main-body-style-obj="{ paddingTop: '32px' }" :tabs="getTabs()">
    <template #tool-btn>
      <a-button v-auth="'admin-case-manage-create'" type="primary" @click="handleEdit('add')">创建案例</a-button>
    </template>
    <template #screen-space>
      <a-row class="page-top" :wrap="false">
        <a-col>
          <a-tree-select
            v-model:value="pageForm.organizationId"
            :loading="getClassLoading"
            tree-default-expand-all
            :field-names="{
              children: 'children',
              label: 'orgName',
              value: 'id'
            }"
            :tree-data="transformedTreeData"
            tree-node-filter-prop="label"
            class="w-400 mr-8"
            @change="getDataList({ offset: 1 })"
          />
        </a-col>
        <a-col>
          <a-select
            ref="select"
            v-model:value="pageForm.isOwner"
            class="w-140"
            :options="caseOptions"
            :field-names="{ label: 'labelName', value: 'labelId' }"
            @change="getDataList({ offset: 1 })"
          />
        </a-col>
      </a-row>
    </template>
    <div class="search-table">
      <div class="list-table">
        <card-list :items="caseList as any" :org-id="pageForm.organizationId as string " @del="del" />
        <g-pagination
          v-model:offset="pageForm.offset"
          v-model:limit="pageForm.limit"
          class="pagination"
          :total="pageForm.total"
          @change="getDataList"
        />
      </div>
    </div>
  </main-card-admin>
  <!-- 删除 -->
  <delConfirmDialog
    :id="delId"
    ref="delConfirmDialogRef"
    :org-id="pageForm.organizationId as string"
    @success="() => getDataList({ offset: 1 })"
  />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { computed, onMounted, ref } from 'vue'
  import { useRouter } from 'vue-router'

  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import useList from '@/hooks/use-list'
  import { adminCaseManageApi, learningCaseManageApi, schoolOrganizationManageApi } from '@/services/api'

  import cardList from '../components/card-list/index.vue'
  import delConfirmDialog from '../components/del-confirm-dialog/index.vue'
  import { CaseStatus, ClassType, PageForm, RecordListItem } from '../types'
  import { getTabs } from '../utils'

  const router = useRouter()
  const orgId = ref<string>('')

  /********************案例************************/

  let caseOptions = ref<CaseStatus[]>([
    {
      labelName: '全部案例',
      labelId: ''
    },
    {
      labelName: '预置案例',
      labelId: '1'
    },
    {
      labelName: '我创建的',
      labelId: '0'
    }
  ])

  /********************班级************************/

  let classOptions = ref<ClassType[]>([])

  //表格
  const {
    pageForm,
    loading,
    dataList: caseList,
    getDataList
  } = useList<PageForm, RecordListItem>(learningCaseManageApi.list, {
    organizationId: '',
    caseType: 0,
    columns: 'createTime',
    isOwner: '',
    order: 'desc'
  })

  const getClassLoading = ref<boolean>(false)
  //全局Loading
  const globalLoading = computed(() => {
    return loading.value || getClassLoading.value
  })

  const delConfirmDialogRef = ref()
  const delId = ref<string>('')
  const del = (id: string) => {
    delConfirmDialogRef.value.open()
    delId.value = id
  }

  //新建
  const handleEdit = (type: 'add' | 'edit', item?: RecordListItem) => {
    if (type === 'add') {
      router.push(`/admin/learning-case-manage/add`)
      return
    }
    router.push(`/admin/learning-case-manage/edit/${item?.id}`)
  }

  // 获取班级列表
  const getClassList = async (): Promise<void> => {
    getClassLoading.value = true
    try {
      const { data } = await schoolOrganizationManageApi.getOrganizationTree({ authFlag: 1 })
      classOptions.value = [...data.map((item: any) => ({ orgName: item.orgName, id: item.id, children: item.children }))]
      console.log('classOptions:', classOptions.value)
      // 默认选择第一个班级
      const idsAtLevelFive = findIdAtLevelFive(classOptions.value[0])
      console.log(idsAtLevelFive[0])
      pageForm.value.organizationId = idsAtLevelFive[0]
      console.log('pageForm.value.organizationId:', pageForm.value.organizationId)
      getDataList()
    } catch (error) {
      console.log(error)
    }
    getClassLoading.value = false
  }
  const transformTreeData = (data: any[]): any[] => {
    return data.map(item => ({
      ...item,
      disabled: !(item.isAuthActive && item.level === 5),
      children: item.children ? transformTreeData(item.children) : []
    }))
  }
  const transformedTreeData = computed(() => transformTreeData(classOptions.value))

  const findIdAtLevelFive = (item: any) => {
    let ids: string[] = []

    if (item.level === 5 && item.isAuthActive) {
      ids.push(item.id)
    }

    if (item.children) {
      for (const child of item.children) {
        ids = ids.concat(findIdAtLevelFive(child))
      }
    }

    return ids
  }

  onMounted(() => {
    getClassList()
    // getDataList()
  })
</script>

<style lang="less" scoped>
  .search-table {
    overflow: auto;

    .list-table {
      height: 620px;
    }

    .pagination {
      position: fixed;
      bottom: 32px;
      z-index: 99;
      background-color: #fff;
    }
  }
</style>
